import store from '../store/index';
import { get } from '@/api/https';
import { ElMessage } from 'element-plus';

//三层对象扁平化
function flatten(permissions) {
  const result = [];
  for (const permissionsKey of permissions) {
    if (permissionsKey.children.length > 0) {
      for (let permissionsKeyKey of permissionsKey.children) {
        if (permissionsKeyKey.children.length > 0) {
          for (let permissionsKeyKeyKey of permissionsKeyKey.children) {
            result.push(permissionsKeyKeyKey);
          }
        }
        result.push(permissionsKeyKey);
      }
    }
    result.push(permissionsKey);
  }
  return result;
}

async function hasPermission(permission) {
  //本来想用toRow，不知道为什么没有该方法
  let PERMISSIONS = store.state.Permissions;
  //页面重新刷新数据获取
  if (PERMISSIONS.length == 0) {
    const {
      code,
      data
    } = await get('/user/get-menu-by-username/', {
      username: localStorage.getItem('user'),
      isGetRole: false
    });
    if (code == 200) {
      PERMISSIONS = flatten(data)
        .filter((item) => item.MENU_TYPE == 3)
        .map(item => item.PERMS);
      store.state.Permissions = PERMISSIONS;
      return PERMISSIONS.includes(permission);
    } else {
      ElMessage({
        type: 'error',
        message: data.message
      });
      return false;
    }
  }
  return PERMISSIONS.includes(permission);
}

export { hasPermission, flatten };
